const Sports = require("../models/sports");
const SportsRecord = require("../models/sportsRecord");

exports.add = async function (sportsRecord) {
  delete sportsRecord.id;
  return SportsRecord.create({
    ...sportsRecord,
  });
};

exports.getRecord = async function (userId, recordDate) {
  let sportsRecord = {};
  const sportsRecordArr = await SportsRecord.findAll({
    where: { recordDate, userId },
    attributes: { exclude: ["updatedAt", "createdAt"] },
    include: {
      model: Sports,
      attributes: ["id", "img", "name", "heat"],
      as: "sports",
    },
  });
  let sumHeat = 0;
  sportsRecordArr.forEach((item) => {
    sumHeat += item.totalHeat;
  });
  sportsRecord.record = sportsRecordArr;
  sportsRecord.sumHeat = parseFloat(sumHeat.toFixed(2));
  return sportsRecord;
};

exports.remove = async function (id) {
  return SportsRecord.destroy({
    where: { id },
    individualHooks: true,
  });
};

exports.update = async function (sportsRecord) {
  const id = sportsRecord.id;
  delete sportsRecord.id;
  delete sportsRecord.sportsId;
  delete sportsRecord.userId;
  return SportsRecord.update(
    {
      ...sportsRecord,
    },
    { where: { id: id }, individualHooks: true }
  );
};
